package co.fitstart.weapp.api.web.controller.course;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;

import co.fitstart.entity.course.ResultReport;
import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.course.schedule.CourseSchedule;
import co.fitstart.entity.courseware.assessment.BasicData;
import co.fitstart.entity.courseware.assessment.PostureJoint;
import co.fitstart.entity.courseware.assessment.StudentAssessment;
import co.fitstart.entity.courseware.fitnessgroup.BatchCourseware;
import co.fitstart.entity.user.Student;
import co.fitstart.entity.user.User;
import co.fitstart.entity.user.bwh.BwhRecord;
import co.fitstart.weapp.api.service.BwhRecordService;
import co.fitstart.weapp.api.service.CourseRoundService;
import co.fitstart.weapp.api.service.CoursewareService;
import co.fitstart.weapp.api.service.UserService;

/**
 * 
 * @author haiyan_xiao
 *
 */
@RestController
@RequestMapping("/individual-rounds/{roundId}")
public class IndividualCoursewareController {

    private static final Logger logger = LoggerFactory.getLogger(StudentTargetController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private CourseRoundService courseRoundService;

    @Autowired
    private CoursewareService coursewareService;

    @Autowired
    private BwhRecordService bwhRecordService;

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/goal", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult getGoal(@RequestParam("unionid") String unionid,
                              @PathVariable("roundId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            
            httpResult.success().message("获取数据成功")
                                .data("goal", coursewareService.loadGoal(courseRound))
                                .data("targets", coursewareService.listBodyDataTarget(courseRound));
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("getGoal() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/student-assessment", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult getAssessment(@RequestParam("unionid") String unionid,
                                    @PathVariable("roundId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            StudentAssessment studentAssessment = coursewareService.loadStudentAssessment(courseRound);
            
            if(studentAssessment == null) {
                BasicData basicData = coursewareService.loadBasicData(courseRound);
                PostureJoint postureJoint = coursewareService.loadPostureJoint(courseRound);
                
                httpResult.success().message("获取数据成功")
                .data("basicData", basicData)
                .data("postureJoint", postureJoint)
                .data("showRecord", false);
            } else {
                httpResult.success().message("获取数据成功")
                .data("basicData", studentAssessment.getBasicData())
                .data("postureJoint", studentAssessment.getPostureJoint())
                .data("showRecord", true);
            }
            
            
            
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("getAssessment() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }
    
    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/student-assessments", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult listAssessment(@RequestParam("unionid") String unionid,
                                     @PathVariable("roundId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            List<StudentAssessment> studentAssessments = coursewareService.listStudentAssessment(courseRound);
            
            httpResult.success().message("获取数据成功")
                                .data("studentAssessments", studentAssessments);
            
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("getAssessment() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }
    
    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @param studentAssessmentId
     * @return
     */
    @RequestMapping(value = "/student-assessments/{studentAssessmentId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult loadAssessment (@RequestParam("unionid") String unionid,
                                     @PathVariable("roundId") Long courseRoundId,
                                     @PathVariable("studentAssessmentId") Long studentAssessmentId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            StudentAssessment studentAssessment = coursewareService.loadStudentAssessment(studentAssessmentId);
            
            httpResult.success().message("获取数据成功")
                                .data("basicData", studentAssessment.getBasicData())
                                .data("postureJoint", studentAssessment.getPostureJoint())
                                .data("showRecord", true);;
            
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("getAssessment() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @param batchId
     * @return
     */
    @RequestMapping(value = "/weekly-plans/{batchId}/dietary", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult getDietary(@RequestParam("unionid") String unionid,
                                 @PathVariable("roundId") Long courseRoundId,
                                 @PathVariable("batchId") Long batchId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(batchId);
            
            if(student == null || batchCourseware == null || batchCourseware.getCourseRound().getStudent() != student) {
                httpResult.fail("1").message("课程异常");
            } else {
                httpResult.success().message("获取数据成功")
                .data("dietary", coursewareService.loadDietary(batchCourseware));
            }
        } catch (Exception e) {
            logger.error("getDietary() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @param week
     * @return
     */
    @RequestMapping(value = "/weekly-plans/dietary", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult getDietaryByWeek(@RequestParam("unionid") String unionid,
                                       @PathVariable("roundId") Long courseRoundId,
                                       @RequestParam("week") int week) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            
            BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(courseRound, week);
            
            httpResult.success().message("获取数据成功")
                                .data("dietary", coursewareService.loadDietary(batchCourseware));
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("getDietaryByWeek() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @param batchId
     * @return
     */
    @RequestMapping(value = "/weekly-plans/{batchId}/exercise", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult getExercise(@RequestParam("unionid") String unionid,
                                  @PathVariable("roundId") Long courseRoundId,
                                  @PathVariable("batchId") Long batchId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(batchId);
            
            if(student == null || batchCourseware == null || batchCourseware.getCourseRound().getStudent() != student) {
                httpResult.fail("1").message("课程异常");
            } else {
                httpResult.success().message("获取数据成功")
                .data("exercise", coursewareService.loadExercise(batchCourseware))
                .data("schedules", coursewareService.listPlannedSchedule(batchCourseware));
            }
        } catch (Exception e) {
            logger.error("getExercise() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @param week
     * @return
     */
    @RequestMapping(value = "/weekly-plans/exercise", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult getExerciseByWeek(@RequestParam("unionid") String unionid,
                                        @PathVariable("roundId") Long courseRoundId,
                                        @RequestParam("week") int week) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            
            BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(courseRound, week);
            
            httpResult.success().message("获取数据成功")
                                .data("exercise", coursewareService.loadExercise(batchCourseware))
                                .data("schedules", coursewareService.listPlannedSchedule(batchCourseware));
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("getExerciseByWeek() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/course-coursewares", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult listCourseCourseware(@RequestParam("unionid") String unionid,
                                           @PathVariable("roundId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            
            List<CourseSchedule> courseSchedules = coursewareService.generallyListScheduleCourseware(courseRound);
            
            httpResult.success().message("获取数据成功")
                                .data("courseSchedules", courseSchedules);
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("listIndividualCourseCourseware() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/result-report", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult getResultReport(@RequestParam("unionid") String unionid,
                                      @PathVariable("roundId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            
            List<BwhRecord> bwhRecords = bwhRecordService.listForResultReport(courseRound);
            ResultReport resultReport = coursewareService.loadResultReport(courseRound);
            
            httpResult.success().message("获取数据成功")
                                .data("bwhRecords", bwhRecords)
                                .data("resultReport", resultReport);
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("getResultReport() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/result-report/summary", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult getResultReportSummary(@RequestParam("unionid") String unionid,
                                             @PathVariable("roundId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            
            ResultReport resultReport = coursewareService.loadResultReport(courseRound);
            
            httpResult.success().message("获取数据成功");
            
            if(resultReport != null) {
                httpResult.data("summary", resultReport.getStudentSummary())
                          .data("wordsToCoach", resultReport.getWordsToCoach());
            }
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("getResultReportSummary() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    @RequestMapping(value = "/result-report/summary", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult editResultReportSummary(@RequestParam("unionid") String unionid,
                                              @PathVariable("roundId") Long courseRoundId,
                                              @RequestParam("summary") String summary,
                                              @RequestParam("wordsToCoach") String wordsToCoach) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            
            coursewareService.editResultReportSummary(courseRound, summary, wordsToCoach);
            
            httpResult.success().message("编辑总结成功");
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("editResultReportSummary() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }
}
